import os

import requests
from lxml import etree

print("=" * 20)
print("* 1.动漫\t8.动物  *")
print("* 2.人物\t9.艺术  *")
print("* 3.风景\t10.宇宙 *")
print("* 4.影视\t11.科技 *")
print("* 5.游戏\t12.简约 *")
print("* 6.美食\t13.机车 *")
print("* 7.治愈\t14.其它 *")
print("=" * 20)
dic = {"1": "dongman", "2": 'renwu', "3": 'fengjing',
       "4": "yingshi", "5": 'youxi', "6": 'meishi',
       "7": 'weimei', "8": 'mengchong', "9": 'yishu',
       "10": 'yuzhou', "11": 'keji', "12": 'jianyue',
       "13": 'jiche', "14": 'qita'}
choose = str(input("请选择："))
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/80.0.3987.116 Safari/537.36 Edg/80.0.361.61 '
}
index = 1
url = ''
imgPath = ''
for page in range(1, 101):
    for key, value in dic.items():
        if key == choose:
            url = f'https://www.bizhihui.com/{value}/{page}/?order=time'
            imgPath = 'img/' + value
            if not os.path.exists(imgPath):
                os.mkdir(imgPath)
    response = requests.get(url=url, headers=headers)
    tree = etree.HTML(response.text)
    target_url = tree.xpath('//ul[@id="item-lists"]//a')
    for i in target_url:
        url = i.xpath('./@href')[0]
        detail = requests.get(url=url, headers=headers)
        detail_tree = etree.HTML(detail.text)
        img_url = detail_tree.xpath('//div[@class="article-pc"]/img')
        for j in img_url:
            img = j.xpath('./@src')[0].split('-')[0]
            name = j.xpath('./@alt')[0].split('电脑壁纸 4K壁纸')[0].replace(" ", "")
            save_img = requests.get(url=img).content
            if index % 2 == 1:
                with open(f'./{imgPath}/{name}.jpg', 'wb') as f:
                    f.write(save_img)
                    index += 1
                print(f"{name}--保存成功！！！")
            else:
                index += 1
                continue
    print(f"第{page}页下载完成！！！")
print("下载完成！！！")
